<template>
    <div class="dashboard-container">
        <!-- 顶部操作栏 -->
        <div class="search">
            <el-form ref="form" :rules="rules" :model="params" label-position="top" size="medium">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="城市">
                            <el-select 
                                filterable 
                                clearable
                                v-model="params.cityId" 
                                placeholder="请选择" 
                                style="width: 100%;"
                                @change="(val)=>handleChangeCity('params', val)"
                            >
                                <el-option v-for="item,index in cityList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="区县">
                            <el-select 
                                filterable 
                                clearable
                                v-model="params.areaId" 
                                placeholder="请选择" 
                                style="width: 100%;"
                                @change="(val)=>handleChangeArea('params', val)"
                            >
                                <el-option v-for="item,index in areaList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="街道" >
                            <el-select clearable filterable v-model="params.streetId" placeholder="请选择" style="width: 100%;">
                                <el-option v-for="item,index in jdList" :key="index" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="创建时间">
                            <el-date-picker
                                v-model="createTime"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                @change="handleChangeTime('createTime')"
                                style="width: 100%;"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="楼盘名称搜索">
                            <el-input clearable placeholder="请输入" v-model="params.name"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 操作按钮 -->
        <div class="opt">
            <el-button type="primary" @click="handleAdd('create')">
                <i class="el-icon-plus"></i>
                新增
            </el-button>
            <el-button type="primary" plain @click="handleSearch">
                <i class="el-icon-search"></i>
                查询
            </el-button>
            <el-button type="primary" plain @click="handleImport">
                导入
            </el-button>
            <el-button type="primary" plain @click="handleExport">
                导出
            </el-button>
            <el-button type="danger" @click="handleTJDelete">
                条件删除
            </el-button>
            
        </div>

        <!-- 内容栏 -->
        <div class="body">
            <!-- 列表 -->
            <el-table :data="list" v-loading="loading">
                <el-table-column label="ID" prop="id" width="100"></el-table-column>
                <el-table-column label="城市" prop="cityName" width="100"></el-table-column>
                <el-table-column label="区县" prop="areaName" width="100"></el-table-column>
                <el-table-column label="街道" prop="streetName" width="100"></el-table-column>
                <el-table-column label="经度" prop="longitude" width="100"></el-table-column>
                <el-table-column label="纬度" prop="latitude" width="100"></el-table-column>
                <el-table-column label="楼盘名称" prop="name">
                    <template slot-scope="{row}">
                        {{ row.name  }} 
                    </template>
                </el-table-column>
                <el-table-column label="详细地址" prop="detailAddress"></el-table-column>
                <el-table-column label="创建时间" prop="createTime"></el-table-column>
                <el-table-column label="操作" width="230px">
                <template slot-scope="{row}">
                    <el-button type="text" @click="handleAdd('update', row)">
                    <i class="el-icon-edit-outline"></i>
                    编辑
                    </el-button>
                </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="page">
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="params.pageIndex+1"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="params.pageCount"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
                </el-pagination>
            </div>
        </div>

        <!-- 新增、编辑 -->
        <el-dialog
            :title="dialogType=='create'?'新增':'编辑'" 
            :visible.sync="dialogVisibleAdd" 
            :close-on-click-modal="false"
            @close="dialogVisibleAdd=false"
            width="500px"
        >
            <el-form  :model="temp" :rules="rulesAdd" ref="formAdd" label-width="80px" label-position="right">
                <el-form-item label="小区名" prop="name">
                    <el-input placeholder="请输入.." v-model="temp.name"></el-input>
                </el-form-item>
                <el-tag type="warning" style="margin-bottom: 3px;margin-left: 80px;">多个别名使用英文|分割例： A小区|B小区</el-tag>
                <el-form-item label="别名" prop="alias">
                    <el-input placeholder="请输入.." v-model="temp.alias"></el-input>
                </el-form-item>
                
                <el-form-item label="城市" prop="cityId" v-if="dialogType=='create'">
                    <el-select 
                        filterable 
                        clearable
                        v-model="temp.cityId" 
                        placeholder="请选择" 
                        style="width: 100%;"
                        @change="(val)=>handleChangeCity('temp', val)"
                    >
                        <el-option v-for="item,index in cityList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="区县"  prop="areaId"  v-if="dialogType=='create'">
                    <el-select 
                        filterable 
                        clearable
                        v-model="temp.areaId" 
                        placeholder="请选择" 
                        style="width: 100%;"
                        @change="(val)=>handleChangeArea('temp', val)"
                    >
                        <el-option v-for="item,index in areaAddList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="街道"  prop="streetId"  v-if="dialogType=='create'">
                    <el-select 
                        filterable 
                        clearable
                        v-model="temp.streetId" 
                        placeholder="请选择" 
                        style="width: 100%;"
                    >
                        <el-option v-for="item,index in jdAddList" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="经度" prop="longitude">
                    <el-input placeholder="请输入.." v-model="temp.longitude"></el-input>
                </el-form-item>
                <el-form-item label="纬度" prop="latitude">
                    <el-input placeholder="请输入.." v-model="temp.latitude"></el-input>
                </el-form-item>
                <el-form-item label="详细地址" prop="detailAddress">
                    <el-input placeholder="请输入.." v-model="temp.detailAddress"></el-input>
                </el-form-item>
            </el-form>
            <div class="opt_btn" style="padding-top: 30px;" >
                <el-button type="primary" @click="handleSubmitAdd('formAdd')" :loading="uploadLoading">提交</el-button>
                <el-button type="primary" @click="dialogVisibleAdd=false" plain>取消</el-button>
            </div>
        </el-dialog>

        <!-- 案例批量导入 -->
        <el-dialog 
            title="楼盘批量导入" 
            :visible.sync="dialogVisible" 
            :close-on-click-modal="false"
            @close="dialogVisible=false"
            width="500px"
        >
            <div v-if="!isuploading">
                <el-form :model="uploadTemp" :rules="rules" ref="form">
                    <el-form-item label="模版">
                        <el-button type="primary" @click="downloadMB">下载</el-button>
                    </el-form-item>
                    
                    <el-form-item label="导入文件" prop="filePath">
                        <el-upload
                            style="text-align: center;"
                            class="upload-demo"
                            drag
                            :action="API_BASE_URL + '/common/uploadFile'"
                            name="file"
                            :on-success="handleSuccess"
                            :before-upload="handleBefore"
                            :on-error="handleError"
                            :limit="1"
                            accept=".zip"
                        >
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <div class="el-upload__tip" slot="tip">只能上传zip文件</div>
                        </el-upload>
                    </el-form-item>  
                    <el-form-item label="导入策略" prop="policy">
                        <el-select clearable filterable v-model="uploadTemp.policy" placeholder="请选择" style="width: 100%;">
                            <el-option v-for="item in POLICY_TYPE_LIST" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <div class="opt_btn" style="padding-top: 30px;" >
                    <el-button type="primary" @click="handleSubmitUpload('form')" :loading="uploadLoading">提交</el-button>
                    <el-button type="primary" @click="dialogVisible=false" plain>取消</el-button>
                </div>
            </div>
            <div v-else>
                {{ progress }}
                <div class="opt_btn" style="padding-top: 30px;" >
                    <el-button type="primary" @click="handleCancelAndClosed">关闭</el-button>
                </div>
            </div>
            
        </el-dialog>

        <!-- 案例导出 -->
        <el-dialog 
            title="楼盘导出" 
            :visible="dialogVisibleExport" 
            width="800px" 
            @close="dialogVisibleExport=false" 
            :close-on-click-modal="false"
        >
            <el-form >
                <el-form-item label="固定字段" v-if="fixedFields.length>0">
                    <el-checkbox  v-model="checkAllFixed" @change="(val)=>handleCheckAllChange('fixed', val)" >全选</el-checkbox>
                    <el-checkbox-group v-model="showFixedFields">
                        <el-checkbox v-for="field in fixedFields" :label="field" :key="field">{{field}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="自定义字段" v-if="customFields.length>0">
                    <el-checkbox v-model="checkAllCustom" @change="(val)=>handleCheckAllChange('custom', val)" >全选</el-checkbox>
                    <el-checkbox-group v-model="showCustomFields">
                        <el-checkbox v-for="field in customFields" :label="field" :key="field">{{field}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <div>
                <el-button type="primary" @click="submitExport" v-loading="loadingExport">导出</el-button>
                <el-button @click="dialogVisibleExport = false">关闭</el-button>
            </div>
        </el-dialog>
        
    </div>
</template>
  
<script>
import { commonGetAreaList, commonGetCityList } from '@/api/common'
import moment from 'moment'
import { transFormValue, transFromCityName } from '@/utils/tools';
import { API_BASE_URL, TARGET_TYPE_LIST, geoTypeList, TransactionSituationList, POLICY_TYPE_LIST } from '@/utils/common'
import * as XLSX from 'xlsx'
import * as FileSaver from 'file-saver'
import axios from 'axios'
import { asyncTaskCancel, asyncTaskInfo } from '@/api/task'
import { 
    communityGetList, 
    communityAsyncImportZip, 
    communityDelete, 
    communityGetExportFieldOptions, 
    communityUpdate,
    communityCreate
} from '@/api/community'

export default {
    name: 'dataTarget',
    data(){
        return {
            POLICY_TYPE_LIST,
            geoTypeList,
            TARGET_TYPE_LIST,
            TransactionSituationList,
            API_BASE_URL,
            rules: {
                propertyType: [{ required: true, message: '请选择案例对象', trigger: 'blur' }],
                filePath: [{ required: true, message: '请上传导入文件', trigger: 'blur' }],
                policy: [{required: true, message: '请选择策略', trigger: 'blur'}],
                geoSystemType: [{required: true, message: '请选择坐标类型', trigger: 'blur'}],
            },
            rulesAdd: {
                streetId: [{ required: true, message: '请选择街道', trigger: 'blur' }],
                cityId: [{ required: true, message: '请选择城市', trigger: 'blur' }],
                areaId: [{ required: true, message: '请选择区县', trigger: 'blur' }],
                name: [{ required: true, message: '请输入小区名', trigger: 'blur' }],
                longitude: [{ required: true, message: '请输入经度', trigger: 'blur' }],
                latitude: [{ required: true, message: '请输入维度', trigger: 'blur' }]
            },
            params: {
                provinceId: 11,  //默认浙江省
                cityId: '', //城市id
                areaId: '',// 区县id
                streetId: '', //街道id
                name: '',
                pageIndex: 0,
                pageCount: 10,
                minCreateTime: '',
                maxCreateTime: '', //创建时间
            },
            exportParams: {},
            createTime: [],
            Time: [],
            cityList: [],
            areaList: [],
            areaAddList: [],
            jdList: [],
            jdAddList: [],
            loading: false,
            list: [],
            total: 0,
            cityListLabel: [],
            dialogVisible: false,
            uploadLoading: false,
            uploadTemp: {
                filePath: '',
                policy: 1
            },
            multipleSelection: [],
            dialogVisibleExport: false,
            loadingExport: false,
            customFields: [], //自定义字段-列表
            fixedFields: [],//固定字段-列表
            showCustomFields: [], //自定义字段-已选择
            showFixedFields: [], //固定字段-已选择
            checkAllFixed: false,
            checkAllCustom: false,
            isuploading: false, //代表上传中
            asyncUploadId: '', //上传中的id,
            progress: '', //上传进度
            dialogVisibleAdd: false,
            dialogType: 'create',
            temp: {}
        }
    },
    async mounted(){
        let data = await commonGetCityList({ geoLevel: 2, provinceId: 11 });
        this.cityList = data;
        this.cityListLabel = data.map(item=>{
            return { label: item.name, value: item.id }
        })
        this.handleSearch();
    },
    methods:{
        //提交新增、编辑楼盘
        handleSubmitAdd(formName){
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                   this.uploadLoading = true;
                   let temp = JSON.parse(JSON.stringify(this.temp))
                   temp.alias = temp.alias.split('|').filter(item=>item)

                //    if(!temp.streetId){
                //         //如果没有填街道，那么根据经纬度自动识别街道信息
                //         // 创建地址解析器实例     
                //         var myGeo = new BMapGL.Geocoder();  
                //         myGeo.getLocation(new BMapGL.Point(temp.longitude, temp.latitude), function(result){      
                //             if (result){      
                //                 console.log(result);      
                //             }      
                //         }); 
                //    }
                //    return;
                   if(this.dialogType == 'create'){
                        //走新增
                        await communityCreate(temp)
                   }else{
                        await communityUpdate(temp)
                        
                   }
                   this.$message.success({ message: '提交成功' })
                   this.uploadLoading = false;
                   this.dialogVisibleAdd = false;
                   this.getData();
                }else {
                    console.log('error submit!!');
                    return false;
                }
            });  
        },
        //下载模版
        downloadMB(){
            axios({
                url: `${API_BASE_URL}/community/getImportTemplateFile`,
                method: 'POST',
                responseType: 'blob'
            }).then((res) => {
                const blob = res.data
                const fileName = '楼盘模版.zip'
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = window.URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                window.URL.revokeObjectURL(elink.href)// 释放对象
                document.body.removeChild(elink)// 移除元素
            })
        },
        //取消并关闭异步上传
        async handleCancelAndClosed(){
            await asyncTaskCancel({ id: this.asyncUploadId });
            this.dialogVisible = false;
        },
        //全选按钮
        handleCheckAllChange(name, val) {
            if(name=='fixed'){
                this.showFixedFields = val ? this.fixedFields : [];
            }
            if(name=='custom'){
                this.showCustomFields = val ? this.customFields : [];
            }
            
        },
        //提交导出
        async submitExport(){
            this.loadingExport = true;
            let params = JSON.parse(JSON.stringify(this.exportParams))
            params.showCustomFields = this.showCustomFields;
            params.showFixedFields = this.showFixedFields;
            axios({
                url: `${API_BASE_URL}/community/export${transFormValue(params)}`,
                method: 'POST',
                responseType: 'blob'
            }).then((res) => {
                const blob = res.data
                const fileName = moment().format('YYYY-MM-DD') +'楼盘导出.xlsx'
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = window.URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                window.URL.revokeObjectURL(elink.href)// 释放对象
                document.body.removeChild(elink)// 移除元素

                this.loadingExport = false;
            })
                
            
        },
        //选择导出的类型
        async handleChangeExportType(){
            let data = await communityGetExportFieldOptions()
            let { customFields, fixedFields } = data;
            this.customFields = customFields.map(item=>item.name).sort();
            this.fixedFields =  fixedFields;
            this.showCustomFields = [];
            this.checkAllFixed = false;
            this.checkAllCustom = false;
        },
        //点击导出
        async handleExport(){
            this.exportParams = JSON.parse(JSON.stringify(this.params));
            this.showCustomFields = [];
            this.showFixedFields = [];
            this.customFields = [];
            this.fixedFields = [];
            this.dialogVisibleExport = true;
            this.loadingExport = false; //加载动画
            this.handleChangeExportType();
        },
        //修改创建时间区间
        handleChangeTime(name){
            if(this[name]){
                if(name=='createTime'){
                    this.params.minCreateTime = moment(this.createTime[0]).valueOf();
                    this.params.maxCreateTime = moment(this.createTime[1]).valueOf();
                }
                
            }else{
                if(name=='createTime'){
                    this.params.minCreateTime = this.params.maxCreateTime = null
                }   
            }
        },
        //点击条件删除
        handleTJDelete(){
            let params = JSON.parse(JSON.stringify(this.params))
            this.$confirm(`此操作将永久删除${this.total}个楼盘, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                await communityDelete(params)
                this.getData();
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
            
        },
        //上传失败
        handleError(){
            this.uploadLoading = false;
        },
        //上传前钩子
        handleBefore(){
            this.uploadLoading = true;
        },
        // 上传成功
        handleSuccess(res, file){
            this.uploadTemp.filePath = res.data
            this.uploadLoading = false;
        },
        // 点击提交
        handleSubmitUpload(formName){
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    let data = await communityAsyncImportZip(this.uploadTemp)
                    this.asyncUploadId = data;
                    this.isuploading = true;
                    let timer = setInterval(async ()=>{
                        let jd = await asyncTaskInfo({ id: data })
                        let { progress, status, output } = jd;
                        if(progress){
                            this.progress = progress;
                        }
                        // 2.已完成 3.已取消 4.失败
                        if(status==4||status==2||status==3){
                            
                            // 取消定时任务
                            clearInterval(timer)
                            
                            let ErrorMessage = JSON.parse(output);

                            if(ErrorMessage.code!=0){
                                this.progress = ErrorMessage.message;
                                return;
                            }

                            if(status==2){
                                this.progress = '上传完成'
                                // 如果成功的，并且有错误信息的，则返回
                                let errorList = [];
                                if(Object.keys(ErrorMessage.data.failureMessage).length != 0){
                                    for(let key in ErrorMessage.data.failureMessage){
                                        errorList.push({ '错误行:': key, '描述': ErrorMessage.data.failureMessage[key] })
                                    }
                                    this.doExport('错误文件', errorList);
                                }
                            }

                            this.getData();
                            
                        }
                        
                    }, 1000)
        
                }else {
                    console.log('error submit!!');
                    return false;
                }
            });  
        },
        doExport(fileName, tableData){
            const worksheet = XLSX.utils.json_to_sheet(tableData)
            const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] }
            const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
            const data = new Blob([excelBuffer], { type: 'application/octet-stream' })
            FileSaver.saveAs(data, `${fileName}.xlsx`)
        },
        // 点击导入
        handleImport(){
            this.uploadTemp = {
                filePath: '',
                policy: 1,
            }
            this.isuploading = false;
            this.progress = '导入中'
            this.dialogVisible = true;
        },
        // 新增、编辑
        handleAdd(type, row){
            this.dialogType = type;
            this.dialogVisibleAdd = true;
            this.uploadLoading = false
            if(type=='create'){
                this.temp = {
                    provinceId: 11,
                    cityId: '',
                    areaId: '',
                    streetId: '',
                    detailAddress: '',
                    latitude: '',
                    longitude: '',
                    alias: ''
                }
            }else{
                this.temp = row
            }
        },
        //修改搜索条件
        handleSearch(){
            this.params.pageIndex = 0;
            this.getData();
        },
        //选择了区县
        async handleChangeArea(name, val){
            if(val){
                if(name=='params'){
                    this.jdList = this.areaList.filter(item=>item.id==val)[0].streets;
                }else if(name=='temp'){
                    this.jdAddList = this.areaAddList.filter(item=>item.id==val)[0].streets;
                }
            }else{
                if(name=='params'){
                    this.jdList = []
                }else if(name=='temp'){
                    this.jdAddList = []
                }
            }
            this[name].streetId = '';
        },
        //改变城市
        async handleChangeCity(name, val){
            if(val){
                // 请求区县信息
                let data = await commonGetAreaList({ geoLevel: 4, cityId: val })
                if(name=='params'){
                    this.areaList = data;
                }else if(name=='temp'){
                    this.areaAddList = data;
                }
                
            }else{
                if(name=='params'){
                    this.areaList = [];
                }else if(name=='temp'){
                    this.areaAddList = []
                }
                
            }
            //清空之前的区县选择
            this[name].areaId = '';
            this[name].streetId = '';
            
        },
        //加载列表数据
        async getData(){
            let params = JSON.parse(JSON.stringify(this.params))
            this.loading = true
            let data = await communityGetList(params)
            this.loading = false;
            this.total = data.totalCount;
            this.list = data.list.map(item=>{
                let { cityName, areaName, streetName } = transFromCityName(item.cityId, item.areaId, item.streetId)
                item.cityName = cityName;
                item.areaName = areaName;
                item.streetName = streetName;
                item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
                item.alias = item.alias.map(item=>item.alias).join('|')
                
                return item;
            });
        },
        
        // 修改每页数量
        handleSizeChange(val){
            this.params.pageIndex = 0;
            this.params.pageCount = val;
            this.getData();
        },
        // 切换分页
        handleCurrentChange(val){
            this.params.pageIndex = val - 1;
            this.getData();
        }
    }
}
</script>

<style lang="scss" scoped>
.dashboard {
    &-container {
      margin: 30px;
      position: relative;
      .opt{
        margin-bottom: 10px;
      }
      .page{
        padding: 20px 0;
        text-align: center;
      }
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
}
</style>
  